package leecode

import "sort"

func topKFrequent692(words []string, k int) (result []string) {
	hashMap := make(map[string]int) //key为字符串 , value为出现的次数
	for i := 0; i < len(words); i++ {
		hashMap[words[i]]++
	}
	//寻找出现次数最多的k个单词的数量
	countArr := make([]int, 0, len(words))
	for _, count := range hashMap {
		countArr = append(countArr, count)
	}
	sort.Ints(countArr)
	countArr = countArr[len(countArr)-k:]
	visited := make(map[string]bool)
	sort.Strings(words)
	for index := len(countArr) - 1; index >= 0; index-- {
		for i := 0; i < len(words); i++ {
			if !visited[words[i]] && hashMap[words[i]] == countArr[index] {
				visited[words[i]] = true
				result = append(result, words[i])
				if len(result) == k {
					return
				}
			}
		}
	}
	return
}
